package maven.jyhs.com.exception.handler;

import maven.jyhs.com.dao.ApiResult;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.net.BindException;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class T03ExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ModelAndView handleRuntimeException(RuntimeException e) {
        ModelAndView modelAndView = new ModelAndView();
        e.printStackTrace();
        modelAndView.setViewName("error");
        modelAndView.addObject("errorMessage", e.getMessage());
        return modelAndView;
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ModelAndView handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("errorMessage", e.getMessage());
        System.out.println("参数异常：" + e.getMessage());
        return modelAndView;
    }



    // 注意：通常不建议捕获所有异常（Exception.class），因为这可能会隐藏其他潜在的错误。
    // 如果确实需要捕获所有异常，请确保这是您想要的行为，并考虑记录更详细的错误信息。
    @ExceptionHandler(Exception.class)
    public ModelAndView handleAllExceptions(Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("errorMessage", "未知异常：" + e.getMessage());
        e.printStackTrace(); // 在生产环境中，通常不建议打印堆栈跟踪到控制台
        // 考虑使用日志框架（如SLF4J）来记录异常
        return modelAndView;
    }



    @ExceptionHandler(value = {MethodArgumentNotValidException.class, HttpMessageNotReadableException.class, BindException.class})
    @ResponseBody
    public ApiResult handleHttpMessageNotValidException(HttpMessageNotReadableException e, BindingResult bindingResult) {
        e.printStackTrace();
        System.out.println("请求体参数异常：" + e.getMessage());
        StringBuilder message = new StringBuilder();
        bindingResult.getFieldErrors().forEach(error -> {
            String defaultMessage = error.getDefaultMessage();
            message.append(defaultMessage).append(";");

        });
        return new ApiResult(201,  message.toString(), null);

    }

    @ExceptionHandler(value = {DataIntegrityViolationException.class})
    @ResponseBody
    public ApiResult handleDataIntegrityViolationException(DataIntegrityViolationException e) {
        e.printStackTrace();
        System.out.println("数据完整性异常：" + e.getMessage());
        return new ApiResult(202,  e.getCause().toString(), null);
    }
}